package net.worlds;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JTextArea;

/**
 * This class extends the OutputStream class to allow output to be printed
 * to a TextArea ...
 */
public class ChatOutputStream extends OutputStream
{

  private StringBuffer strBuffer = new StringBuffer ();
  private boolean closed = false;
  boolean err;
  Color normalColor = Color.white;
  Color errorColor = new Color(237, 185, 102);
  PrintStream main;

  // private byte savedByte;
  // private boolean savedByteAvailable = false;

  public ChatOutputStream (boolean err, PrintStream main)
  {
    super ();
    this.err = err;
    this.main = main;
  }

  /** method to write a char */
  public void write (int i)
       throws IOException
  {
    if (closed)
      return;

    strBuffer.append ( (char) i);

  }

  /** write an array of bytes */
    @Override
  public void write (byte[] b, int offset, int length)
       throws IOException
  {
    if (closed)
      return;

    if (b == null)
      throw new NullPointerException ("The byte array is null");
    if (offset < 0 || length < 0 || (offset+length) > b.length)
      throw new IndexOutOfBoundsException ("offset and length are negative or extend outside array bounds");

    String str = new String (b, offset, length);
    strBuffer.append (str);
  }

  /** flush (from OutputStream) */
    @Override
  public void flush ()
  {
    if (closed || strBuffer.length() == 0 || strBuffer.toString().trim().isEmpty())
      return;
    if(err)
        Chat.addChat(errorColor, strBuffer.toString () );
    else
        Chat.addChat(normalColor, strBuffer.toString () );
    main.print(strBuffer.toString());
    int length = strBuffer.length ();
    strBuffer.delete (0, length);
  }

  public void close ()
  {
    flush ();
    strBuffer = null;
    closed = true;
  }

}